﻿using Microsoft.Data.Sqlite;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Xml.Linq;

namespace objass
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private SqliteConnection? connection;
        public string FilePath { get; set; }

        // 定义常量 DBField_Name
        public const string DBTable_Name = "objAssName";
        public const string DBTable_Rel = "objAssRelevent";
        public const string DBTable_RelType = "objAssRelType";

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
        }

        public void CloseSQLiteDatabase()
        {
            if (connection != null)
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
                connection.Dispose();
                connection = null;
            }
            FilePath = "";
        }


        public void CreateSQLiteDatabase(string filePath)
        {
            // 更新成员变量 FilePath
            FilePath = filePath;

            // 创建 SQLite 数据库文件
            if (!File.Exists(FilePath))
            {
                File.Create(FilePath).Dispose();
            }

            // 关闭并释放之前的连接
            connection?.Dispose();

            // 使用成员变量 connection
            connection = new SqliteConnection($"Data Source={FilePath};");
            connection.Open();

            string createTableQuery = $@"
                                                CREATE TABLE IF NOT EXISTS {DBTable_Name} (
                                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                    name TEXT NOT NULL,
                                                    content TEXT,
                                                    iscategory INTEGER DEFAULT 0,
                                                    UNIQUE(name)
                                                );";
            using (var command = new SqliteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
            createTableQuery = $@"
                                                CREATE TABLE IF NOT EXISTS {DBTable_RelType} (
                                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                    name1 TEXT NOT NULL,
                                                    name2 TEXT NOT NULL,
                                                    delflag INTEGER DEFAULT 0,
                                                    UNIQUE(name1, name2)
                                                );";
            using (var command = new SqliteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
            createTableQuery = $@"
                                                CREATE TABLE IF NOT EXISTS {DBTable_Rel} (
                                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                    name1 TEXT NOT NULL,
                                                    name2 TEXT NOT NULL,
                                                    reltype TEXT,
                                                    content TEXT,
                                                    UNIQUE(name1, name2)
                                                );";
            using (var command = new SqliteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }

            AddNode("类别", true);
            AddNode("文档信息", false);
        }

        public static bool IsTableExist(string tableName, string filePath, SqliteConnection? connection)
        {
            bool tableExists = false;
            if (!string.IsNullOrEmpty(filePath))
            {
                connection ??= new SqliteConnection($"Data Source={filePath};");
                // 确保连接是打开的
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }

                string query = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=@tableName";
                using var command = new SqliteCommand(query, connection);
                command.Parameters.AddWithValue("@tableName", tableName);
                long count = (long)command.ExecuteScalar();
                tableExists = count > 0;
            }
            return tableExists;
        }

        public static bool VerifyDatabase(string filePath, SqliteConnection? connection)
        {
            if (!IsTableExist(DBTable_Name, filePath, connection))
            {
                return false;
            }
            if (!IsTableExist(DBTable_Rel, filePath, connection))
            {
                return false;
            }
            if (!IsTableExist(DBTable_RelType, filePath, connection))
            {
                return false;
            }
            // 这里应该添加返回 true 的逻辑，因为前面的检查都通过了
            return true;
        }
        //添加一个节点
        public bool AddNode(string name, bool iscategory)
        {
            bool bExist = false;
            if (!string.IsNullOrEmpty(name))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    string query = $"INSERT INTO {DBTable_Name} (name, content, iscategory) VALUES (@name, '', @iscategory)";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name", name);
                        command.Parameters.AddWithValue("@iscategory", iscategory);
                        command.ExecuteNonQuery();
                    }
                    bExist = true;
                }
            }
            return bExist;
        }

        //添加一批节点
        public void AddNodes(string names)
        {
            if (!string.IsNullOrEmpty(names))
            {
                // 使用英文逗号和中文逗号分割字符串
                string[] nameArray = names.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var name in nameArray)
                {
                    if (!string.IsNullOrEmpty(name))
                    {
                        var nodename = name.Trim();
                        if (!IsNodeExist(nodename))
                        {
                            var bExist = AddNode(nodename, false);
                        }
                    }
                }
            }
        }

        public bool DeleteNode(string name)
        {
            bool bExist = true;
            if (!string.IsNullOrEmpty(name))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    string query = $"DELETE FROM {DBTable_Name} WHERE name = @name";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name", name);
                        command.ExecuteNonQuery();
                    }
                    bExist = false;
                }
            }
            return bExist;
        }

        public bool AddRelName(string relname1, string relname2)
        {
            bool bExist = false;
            if (!string.IsNullOrEmpty(relname1) && !string.IsNullOrEmpty(relname2))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    string query = $"SELECT COUNT(*) FROM {DBTable_RelType} WHERE name1 = @name1 and name2 = @name2";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", relname1);
                        command.Parameters.AddWithValue("@name2", relname2);
                        bExist = (long)command.ExecuteScalar() > 0;
                    }

                    if (bExist)
                    {
                        query = $"UPDATE {DBTable_RelType} SET delflag = 0 WHERE name1 = @name1 and name2 = @name2";
                        using (var command = new SqliteCommand(query, connection))
                        {
                            command.Parameters.AddWithValue("@name1", relname1);
                            command.Parameters.AddWithValue("@name2", relname2);
                            command.ExecuteNonQuery();
                        }
                    }
                    else
                    {
                        query = $"INSERT INTO {DBTable_RelType} (name1, name2, delflag) VALUES (@name1, @name2, @delflag)";
                        using (var command = new SqliteCommand(query, connection))
                        {
                            command.Parameters.AddWithValue("@name1", relname1);
                            command.Parameters.AddWithValue("@name2", relname2);
                            command.Parameters.AddWithValue("@delflag", 0);
                            command.ExecuteNonQuery();
                        }
                    }

                    bExist = true;
                }
            }
            return bExist;
        }

        public bool DelRelName(string relname1, string relname2)
        {
            bool bExist = false;
            if (!string.IsNullOrEmpty(relname1) && !string.IsNullOrEmpty(relname2))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    var query = $"UPDATE {DBTable_RelType} SET delflag = 1 WHERE name1 = @name1 and name2 = @name2";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", relname1);
                        command.Parameters.AddWithValue("@name2", relname2);
                        command.ExecuteNonQuery();
                    }
                    bExist = true;
                }
            }
            return bExist;
        }

        public bool AddRel(string nameA, string nameB, string reltype)
        {
            bool bExist = false;
            if (!string.IsNullOrEmpty(nameA) && !string.IsNullOrEmpty(nameB))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    // 检查 nameA 是否存在，如果不存在则添加
                    if (!IsNodeExist(nameA))
                    {
                        AddNode(nameA, false);
                    }

                    // 检查 nameB 是否存在，如果不存在则添加
                    if (!IsNodeExist(nameB))
                    {
                        AddNode(nameB, false);
                    }

                    DeleteRel(nameA, nameB);

                    string query = $"INSERT INTO {DBTable_Rel} (name1, name2, reltype, content) VALUES (@name1, @name2, @reltype, '')";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", nameA);
                        command.Parameters.AddWithValue("@name2", nameB);
                        command.Parameters.AddWithValue("@reltype", reltype);
                        command.ExecuteNonQuery();
                    }
                    bExist = true;
                }
            }
            return bExist;
        }

        public bool DeleteRel(string nameA, string nameB)
        {
            bool bExist = true;
            if (!string.IsNullOrEmpty(nameA) && !string.IsNullOrEmpty(nameB))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }

                    string query = $"DELETE FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", nameA);
                        command.Parameters.AddWithValue("@name2", nameB);
                        command.ExecuteNonQuery();
                    }
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", nameB);
                        command.Parameters.AddWithValue("@name2", nameA);
                        command.ExecuteNonQuery();
                    }
                    bExist = false;
                }
            }
            return bExist;
        }

        public bool IsNodeExist(string name)
        {
            bool bExist = false;
            if (!string.IsNullOrEmpty(name))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }
                    string query = $"SELECT COUNT(*) FROM {DBTable_Name} WHERE name = @name";
                    using var command = new SqliteCommand(query, connection);
                    command.Parameters.AddWithValue("@name", name);
                    long count = (long)command.ExecuteScalar();
                    bExist = count > 0;
                }
            }
            return bExist;
        }

        public enum RelStatus
        {
            None = 0,
            Direct = 1,
            Inverse = 2
        }

        public RelStatus IsRelExist(string nameA, string nameB)
        {
            RelStatus status = RelStatus.None;
            if (!string.IsNullOrEmpty(nameA) && !string.IsNullOrEmpty(nameB))
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (connection == null)
                    {
                        connection = new SqliteConnection($"Data Source={FilePath};");
                        connection.Open();
                    }
                    string query = $"SELECT COUNT(*) FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@name1", nameA);
                        command.Parameters.AddWithValue("@name2", nameB);
                        long count = (long)command.ExecuteScalar();
                        if (count > 0)
                        {
                            status = RelStatus.Direct;
                        }
                    }
                    if (status == RelStatus.None)
                    {
                        using var command = new SqliteCommand(query, connection);
                        command.Parameters.AddWithValue("@name1", nameB);
                        command.Parameters.AddWithValue("@name2", nameA);
                        long count = (long)command.ExecuteScalar();
                        if (count > 0)
                        {
                            status = RelStatus.Inverse;
                        }
                    }
                }
            }
            return status;
        }

        protected List<string> SearchInverse(string name, bool bRel)
        {
            name = name.Split(':')[0];
            var searchResults = new List<string>();
            if (!bRel && IsNodeForbidPass(name))
            {
                return searchResults;
            }
            string query = "SELECT * FROM objAssRelevent WHERE name1 = @searchText OR name2 = @searchText";
            using (var command = new SqliteCommand(query, connection))
            {
                command.Parameters.AddWithValue("@searchText", name);
                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var relparts = reader["reltype"].ToString().Split("|");
                    string result;
                    string reltype;
                    if (reader["name1"].ToString() == name)
                    {
                        result = reader["name2"].ToString();
                        reltype = relparts[0];
                    }
                    else if (reader["name2"].ToString() == name)
                    {
                        result = reader["name1"].ToString();
                        reltype = relparts[1];
                    }
                    else
                    {
                        continue;
                    }
                    if (IsNodeForbidPass(result))
                    {
                        result += "*";
                    }
                    if (bRel && relparts.Length >= 2)
                    {
                        result += ":" + reltype;
                    }
                    searchResults.Add(result);
                }
            }
            return searchResults;
        }

        public List<List<string>> Search(string searchText)
        {
            const int maxCol = 4;
            var searchResults = new List<List<string>>(maxCol);
            for (int i = 0; i < maxCol; i++)
            {
                searchResults.Add([]);
            }

            if (string.IsNullOrEmpty(searchText) || string.IsNullOrEmpty(FilePath))
            {
                return searchResults;
            }
            if (connection == null)
            {
                connection = new SqliteConnection($"Data Source={FilePath};");
                connection.Open();
            }
            var alls = new HashSet<string>
            {
                searchText
            };
            var last = new List<string>
            {
                searchText
            };
            int currentCol = 0;
            while (currentCol < maxCol)
            {
                var current = new List<string>();
                foreach (var name in last)
                {
                    var inverses = SearchInverse(name, (currentCol == 0));
                    foreach (var inverse in inverses)
                    {
                        var part0 = inverse.Split(':')[0];
                        //如果part0的结尾是*，那么去掉
                        if (part0.EndsWith("*"))
                        {
                            part0 = part0.Substring(0, part0.Length - 1);
                        }
                        if (!alls.Contains(part0))
                        {
                            current.Add(inverse);
                            alls.Add(part0);
                        }
                    }
                }
                if (current.Count <= 0)
                {
                    break;
                }
                searchResults[currentCol] = current;
                last = current;
                currentCol++;
            }
            return searchResults;
        }

        public string GetNodeContent(string name)
        {
            string content = "";
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"SELECT content FROM {DBTable_Name} WHERE name = @name";
                using var command = new SqliteCommand(query, connection);
                command.Parameters.AddWithValue("@name", name);
                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    content = reader["content"].ToString();
                }
            }
            return content;
        }

        public bool IsNodeForbidPass(string name)
        {
            bool bForbidPass = false;
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"SELECT iscategory FROM {DBTable_Name} WHERE name = @name";
                using var command = new SqliteCommand(query, connection);
                command.Parameters.AddWithValue("@name", name);
                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    bForbidPass = (long)reader["iscategory"] > 0;
                }
            }
            return bForbidPass;
        }

        public void SaveNode(string name, string content, bool ForbidPass)
        {
            //如果name不存在，则添加，否则更新
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                // 检查记录是否存在
                string query = $"SELECT COUNT(*) FROM {DBTable_Name} WHERE name = @name";
                long count;
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@name", name);
                    count = (long)command.ExecuteScalar();
                }
                if (count <= 0)
                {
                    // 插入新记录
                    query = $"INSERT INTO {DBTable_Name} (name, content, iscategory) VALUES (@name, @content, @iscategory)";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@content", content);
                        command.Parameters.AddWithValue("@name", name);
                        command.Parameters.AddWithValue("@iscategory", ForbidPass);
                        command.ExecuteNonQuery();
                    }
                }
                else
                {
                    // 更新记录
                    query = $"UPDATE {DBTable_Name} SET content = @content, iscategory = @iscategory WHERE name = @name";
                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@content", content);
                        command.Parameters.AddWithValue("@name", name);
                        command.Parameters.AddWithValue("@iscategory", ForbidPass);
                        command.ExecuteNonQuery();
                    }
                }
            }
        }

        public void SaveNodeContent(string name, string content)
        {
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"UPDATE {DBTable_Name} SET content = @content WHERE name = @name";
                using var command = new SqliteCommand(query, connection);
                command.Parameters.AddWithValue("@content", content);
                command.Parameters.AddWithValue("@name", name);
                command.ExecuteNonQuery();
            }
        }

        public string SwapParts(string input)
        {
            // 使用 String.Split 方法按 '|' 分割字符串
            string[] parts = input.Split('|');

            // 检查是否有两个部分
            if (parts.Length == 2)
            {
                // 交换部分并返回新的字符串
                return parts[1] + "|" + parts[0];
            }
            else
            {
                // 如果不是两个部分，可以抛出一个异常或者返回一个特定值
                // 这里我们选择抛出一个异常来表示输入格式不正确
                throw new ArgumentException("The input string does not have exactly two parts separated by '|'.");
            }
        }

        public void SaveRelName(string nodeNameA, string nodeNameB, string text)
        {
            if (!string.IsNullOrEmpty(nodeNameA) && !string.IsNullOrEmpty(nodeNameB) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }

                // 检查记录是否存在
                string checkQuery = $"SELECT COUNT(*) FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                long count;
                int existType = 0; //0-不存在，1-正向，2-反向
                using (var command = new SqliteCommand(checkQuery, connection))
                {
                    command.Parameters.AddWithValue("@name1", nodeNameA);
                    command.Parameters.AddWithValue("@name2", nodeNameB);
                    count = (long)command.ExecuteScalar();
                    if (count > 0)
                    {
                        existType = 1;
                    }
                }

                if (count <= 0)
                {
                    checkQuery = $"SELECT COUNT(*) FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                    using (var command = new SqliteCommand(checkQuery, connection))
                    {
                        command.Parameters.AddWithValue("@name1", nodeNameB);
                        command.Parameters.AddWithValue("@name2", nodeNameA);
                        count = (long)command.ExecuteScalar();
                    }
                    if (count > 0)
                    {
                        existType = 2;
                    }
                }

                switch (existType)
                {
                    case 0:
                        // 插入新记录
                        string insertQuery = $"INSERT INTO {DBTable_Rel} (name1, name2, reltype) VALUES (@name1, @name2, @text)";
                        using (var command = new SqliteCommand(insertQuery, connection))
                        {
                            command.Parameters.AddWithValue("@text", text);
                            command.Parameters.AddWithValue("@name1", nodeNameA);
                            command.Parameters.AddWithValue("@name2", nodeNameB);
                            command.ExecuteNonQuery();
                        }
                        break;
                    case 1:
                        // 更新记录-正向
                        string updateQuery = $"UPDATE {DBTable_Rel} SET reltype = @text WHERE name1 = @name1 AND name2 = @name2";
                        using (var command = new SqliteCommand(updateQuery, connection))
                        {
                            command.Parameters.AddWithValue("@text", text);
                            command.Parameters.AddWithValue("@name1", nodeNameA);
                            command.Parameters.AddWithValue("@name2", nodeNameB);
                            command.ExecuteNonQuery();
                        }
                        break;
                    case 2:
                        // 更新记录-反向
                        updateQuery = $"UPDATE {DBTable_Rel} SET reltype = @text WHERE name1 = @name1 AND name2 = @name2";
                        using (var command = new SqliteCommand(updateQuery, connection))
                        {
                            command.Parameters.AddWithValue("@text", SwapParts(text));
                            command.Parameters.AddWithValue("@name1", nodeNameB);
                            command.Parameters.AddWithValue("@name2", nodeNameA);
                            command.ExecuteNonQuery();
                        }
                        break;
                }

                if (existType == 0)
                {
                }
                else
                {
                }
            }
        }

        public Dictionary<string, string> GetRelNodes(string nodeNameA)
        {
            var relNodes = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(nodeNameA) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"SELECT * FROM {DBTable_Rel} WHERE name1 = @name1";
                using var command1 = new SqliteCommand(query, connection);
                command1.Parameters.AddWithValue("@name1", nodeNameA);
                using var reader1 = command1.ExecuteReader();
                while (reader1.Read())
                {
                    var name = reader1["name2"].ToString();
                    var reltype = reader1["reltype"].ToString();
                    relNodes.Add(name, reltype);
                }
                query = $"SELECT * FROM {DBTable_Rel} WHERE name2 = @name2";
                using var command2 = new SqliteCommand(query, connection);
                command2.Parameters.AddWithValue("@name2", nodeNameA);
                using var reader2 = command2.ExecuteReader();
                while (reader2.Read())
                {
                    var name = reader2["name1"].ToString();
                    var reltype = reader2["reltype"].ToString();
                    reltype = SwapParts(reltype);
                    if (!relNodes.ContainsKey(name))
                    {
                        relNodes.Add(name, reltype);
                    }
                }
            }
            return relNodes;
        }

        public string GetRelName(string nodeNameA, string nodeNameB)
        {
            string relName = "";
            if (!string.IsNullOrEmpty(nodeNameA) && !string.IsNullOrEmpty(nodeNameB) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"SELECT reltype FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@name1", nodeNameA);
                    command.Parameters.AddWithValue("@name2", nodeNameB);
                    using var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        relName = reader["reltype"].ToString();
                    }
                }
                if (relName == "")
                {
                    query = $"SELECT reltype FROM {DBTable_Rel} WHERE name1 = @name1 AND name2 = @name2";
                    using var command = new SqliteCommand(query, connection);
                    command.Parameters.AddWithValue("@name1", nodeNameB);
                    command.Parameters.AddWithValue("@name2", nodeNameA);
                    using var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        relName = reader["reltype"].ToString();
                        relName = SwapParts(relName);
                    }
                }
            }
            return relName;
        }
        public HashSet<string> GetRelTypes()
        {
            var relNames = new HashSet<string>();

            if (!string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }

                string query = $"SELECT * FROM {DBTable_RelType} WHERE delflag = 0";
                using var command = new SqliteCommand(query, connection);
                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var name = reader["name1"].ToString() + "|" + reader["name2"].ToString();
                    relNames.Add(name);
                }
            }

            return relNames;
        }

        //判断RelType是否翻转
        public bool IsRelTypeRevert(string relType)
        {
            //解析|分割的relType到name1,name2
            string[] parts = relType.Split('|');
            var relType_name1 = parts[0];
            bool isRevert = false;
            if (!string.IsNullOrEmpty(relType) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }

                string query = $"SELECT COUNT(*) FROM {DBTable_RelType} WHERE name2 = @relType";
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@relType", relType_name1);
                    long count = (long)command.ExecuteScalar();
                    isRevert = count > 0;
                }
            }
            return isRevert;
        }

        public List<string> GetNodeNames()
        {
            var nodeNames = new List<string>();

            if (!string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }

                string query = $"SELECT name FROM {DBTable_Name}";
                using var command = new SqliteCommand(query, connection);
                using var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    nodeNames.Add(reader["name"].ToString());
                }
            }

            return nodeNames;
        }

        public void ChangeNodeName(string nodeName, string newName)
        {
            //这里不检查newName是否已存在，在外面检查
            if (!string.IsNullOrEmpty(nodeName) && !string.IsNullOrEmpty(newName) && !string.IsNullOrEmpty(FilePath))
            {
                if (connection == null)
                {
                    connection = new SqliteConnection($"Data Source={FilePath};");
                    connection.Open();
                }
                string query = $"UPDATE {DBTable_Name} SET name = @newName WHERE name = @nodeName";
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@newName", newName);
                    command.Parameters.AddWithValue("@nodeName", nodeName);
                    command.ExecuteNonQuery();
                }

                //更新所有相关的关系
                query = $"UPDATE {DBTable_Rel} SET name1 = @newName WHERE name1 = @nodeName";
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@newName", newName);
                    command.Parameters.AddWithValue("@nodeName", nodeName);
                    command.ExecuteNonQuery();
                }
                query = $"UPDATE {DBTable_Rel} SET name2 = @newName WHERE name2 = @nodeName";
                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@newName", newName);
                    command.Parameters.AddWithValue("@nodeName", nodeName);
                    command.ExecuteNonQuery();
                }
            }
        }
    }

}
